import type { ReactNode } from 'react';
import { Component } from 'react';
import ReactDOM from 'react-dom';
import { Modal } from 'antd'

import type { ModalProps } from 'antd'

interface DialogProps extends ModalProps {
  content: ReactNode
  onCancel?: (e?: any) => Promise<any>
  onOk?: (e?: any) => Promise<any> | Promise<any>
}

// 在最新的antd5.0版本中，统一了<Modal/> 和 Modal 的样式，所以没有必要再单独封装该组件了

// 设置默认的Modal样式
export const modalConfig = {
  okText: '确定',
  cancelText: '取消',
  closable: true,
  keyboard: true,
  icon: null,
  destroyOnClose: true,
  maskClosable: false,
  centered: true,
  bodyStyle: {
    maxHeight: 'calc(80vh - 50px)',
    overflow: 'auto',
  },
};

class DialogBox extends Component {

  // @ts-ignore
  state: {
    open: boolean;
    hideCancel: boolean;
    options: DialogProps;
    isLoading: boolean;
  }
  constructor(props: DialogProps) {
    super(props);
    this.state = {
      open: false,
      hideCancel: false,
      options: {} as DialogProps,
      isLoading: false,
    };
  }

  //打开提示框

  //取消
  info(options: DialogProps = {} as DialogProps) {
    this.setState({
      hideCancel: true,
      open: true,
      options,
    });
  }
  //确认
  confirm(options: DialogProps = {} as DialogProps) {
    this.setState({
      hideCancel: false,
      open: true,
      options,
    });
  }

  close() {
    this.setState({
      hideCancel: false,
      open: false,
      options: {},
    });
  }

  async onOk(e: any) {
    if (this.state.options.onOk) {
      await this.state.options.onOk(e);
    }
    this.close();
  }

  async onCancel(e: any) {
    const className = (e.currentTarget.className || '').toLowerCase();
    if (this.state.options.onCancel) {
      await this.state.options.onCancel(className == 'ant-modal-close' ? 'onClose' : 'onCancel');
    }
    this.close();
  }
  render() {
    const cancelButtonProps: any = {
      style: { visibility: this.state.hideCancel ? 'hidden' : 'visible' },
    };
    return (
      <Modal
        open={this.state.open}
        cancelButtonProps={cancelButtonProps}
        {...modalConfig}
        {...this.state.options}
        onOk={async (e) => {
          this.setState({ isLoading: true })
          try {
            await this.onOk(e)
          } catch (err) {
            throw err
          } finally {
            this.setState({ isLoading: false })
          }
        }}
        okButtonProps={{ loading: this.state.isLoading }}
        onCancel={async (e) => {
          await this.onCancel(e)
        }}
      >{this.state.options.content}</Modal>
    );
  }
}

const div = document.createElement('div');
document.body.appendChild(div);

// eslint-disable-next-line react/no-render-return-value
const Dialog: DialogBox = ReactDOM.render(<DialogBox />, div) as unknown as DialogBox;
export default Dialog;
